home *** CD-ROM | disk | FTP | other *** search
/ Mac Easy 2010 May / Mac Life Ubuntu.iso / casper / filesystem.squashfs / usr / share / hplip / prnt / cups.py < prev    next >
Encoding:
Python Source  |  2009-04-14  |  22.8 KB  |  721 lines

  1. # -*- coding: utf-8 -*-
  2. #
  3. # (c) Copyright 2003-2009 Hewlett-Packard Development Company, L.P.
  4. #
  5. # This program is free software; you can redistribute it and/or modify
  6. # it under the terms of the GNU General Public License as published by
  7. # the Free Software Foundation; either version 2 of the License, or
  8. # (at your option) any later version.
  9. #
  10. # This program is distributed in the hope that it will be useful,
  11. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  12. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13. # GNU General Public License for more details.
  14. #
  15. # You should have received a copy of the GNU General Public License
  16. # along with this program; if not, write to the Free Software
  17. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307 USA
  18. #
  19. # Author: Don Welch
  20. #
  21.  
  22. # Std Lib
  23. import os
  24. import os.path
  25. import gzip
  26. import re
  27. import time
  28. import urllib
  29. import tempfile
  30. import glob
  31.  
  32. # Local
  33. from base.g import *
  34. from base import utils, models
  35.  
  36. # Handle case where cups.py (via device.py) is loaded
  37. # and cupsext doesn't exist yet. This happens in the
  38. # installer and in a fresh sandbox if the Python extensions
  39. # aren't installed yet.
  40. try:
  41.     current_language = os.getenv("LANG")
  42.     newlang = "C"
  43.  
  44.     # this is a workaround due CUPS rejecting all encoding except ASCII
  45.     # and utf-8
  46.     # if the locale contains the encoding, switch to the same locale,
  47.     # but with utf-8 encoding. Otherwise use C locale.
  48.     if current_language is not None and current_language.count('.'):
  49.         newlang, encoding = current_language.split('.')
  50.         newlang += ".UTF-8"
  51.  
  52.     os.environ['LANG'] = newlang
  53.  
  54.     # the same works for LC_CTYPE, in case it's not set
  55.     current_ctype = os.getenv("LC_CTYPE")
  56.     newctype = "C"
  57.  
  58.     if current_ctype is not None and current_ctype.count('.'):
  59.         newctype, encoding = current_ctype.split('.')
  60.         newctype += ".UTF-8"
  61.  
  62.     os.environ['LC_CTYPE'] = newctype
  63.  
  64.     import cupsext
  65.  
  66.     # restore the old env values
  67.     if current_ctype is not None:
  68.         os.environ['LC_CTYPE'] = current_ctype
  69.  
  70.     if current_language is not None:
  71.         os.environ['LANG'] = current_language
  72.  
  73. except ImportError:
  74.     if not os.getenv("HPLIP_BUILD"):
  75.         log.warn("CUPSEXT could not be loaded. Please check HPLIP installation.")
  76.         sys.exit(1)
  77.  
  78.  
  79. IPP_PRINTER_STATE_IDLE = 3
  80. IPP_PRINTER_STATE_PROCESSING = 4
  81. IPP_PRINTER_STATE_STOPPED = 5
  82.  
  83. # Std CUPS option types
  84. PPD_UI_BOOLEAN = 0   # True or False option
  85. PPD_UI_PICKONE = 1   # Pick one from a list
  86. PPD_UI_PICKMANY = 2  # Pick zero or more from a list
  87.  
  88. # Non-std: General
  89. UI_SPINNER = 100           # Simple spinner with opt. suffix (ie, %)
  90. UI_UNITS_SPINNER = 101     # Spinner control w/pts, cm, in, etc. units (not impl.)
  91. UI_BANNER_JOB_SHEETS = 102 # dual combos for banner job-sheets
  92. UI_PAGE_RANGE = 103        # Radio + page range entry field
  93.  
  94. # Non-std: Job storage
  95. UI_JOB_STORAGE_MODE = 104      # Combo w/linkage
  96. UI_JOB_STORAGE_PIN = 105       # Radios w/PIN entry
  97. UI_JOB_STORAGE_USERNAME = 106  # Radios w/text entry
  98. UI_JOB_STORAGE_ID = 107        # Radios w/text entry
  99. UI_JOB_STORAGE_ID_EXISTS = 108 # Combo
  100.  
  101.  
  102. # ipp_op_t
  103. IPP_PAUSE_PRINTER = 0x0010
  104. IPP_RESUME_PRINTER = 0x011
  105. IPP_PURGE_JOBS = 0x012
  106. CUPS_GET_DEFAULT = 0x4001
  107. CUPS_GET_PRINTERS = 0x4002
  108. CUPS_ADD_MODIFY_PRINTER = 0x4003
  109. CUPS_DELETE_PRINTER = 0x4004
  110. CUPS_GET_CLASSES = 0x4005
  111. CUPS_ADD_MODIFY_CLASS = 0x4006
  112. CUPS_DELETE_CLASS = 0x4007
  113. CUPS_ACCEPT_JOBS = 0x4008
  114. CUPS_REJECT_JOBS = 0x4009
  115. CUPS_SET_DEFAULT = 0x400a
  116. CUPS_GET_DEVICES = 0x400b
  117. CUPS_GET_PPDS = 0x400c
  118. CUPS_MOVE_JOB = 0x400d
  119. CUPS_AUTHENTICATE_JOB = 0x400e
  120.  
  121. # ipp_jstate_t
  122. IPP_JOB_PENDING = 3    # Job is waiting to be printed
  123. IPP_JOB_HELD = 4       # Job is held for printing
  124. IPP_JOB_PROCESSING = 5 # Job is currently printing
  125. IPP_JOB_STOPPED = 6    # Job has been stopped
  126. IPP_JOB_CANCELLED = 7  # Job has been cancelled
  127. IPP_JOB_ABORTED = 8    # Job has aborted due to error
  128. IPP_JOB_COMPLETED = 8  # Job has completed successfully
  129.  
  130. # ipp_status_e
  131. IPP_OK = 0x0000 # successful-ok
  132. IPP_OK_SUBST = 0x001 # successful-ok-ignored-or-substituted-attributes
  133. IPP_OK_CONFLICT = 0x002 # successful-ok-conflicting-attributes
  134. IPP_OK_IGNORED_SUBSCRIPTIONS = 0x003 # successful-ok-ignored-subscriptions
  135. IPP_OK_IGNORED_NOTIFICATIONS = 0x004 # successful-ok-ignored-notifications
  136. IPP_OK_TOO_MANY_EVENTS = 0x005 # successful-ok-too-many-events
  137. IPP_OK_BUT_CANCEL_SUBSCRIPTION = 0x006 # successful-ok-but-cancel-subscription
  138. IPP_OK_EVENTS_COMPLETE = 0x007 # successful-ok-events-complete
  139. IPP_REDIRECTION_OTHER_SITE = 0x300
  140. IPP_BAD_REQUEST = 0x0400 # client-error-bad-request
  141. IPP_FORBIDDEN = 0x0401 # client-error-forbidden
  142. IPP_NOT_AUTHENTICATED = 0x0402 # client-error-not-authenticated
  143. IPP_NOT_AUTHORIZED = 0x0403 # client-error-not-authorized
  144. IPP_NOT_POSSIBLE = 0x0404 # client-error-not-possible
  145. IPP_TIMEOUT = 0x0405 # client-error-timeout
  146. IPP_NOT_FOUND = 0x0406 # client-error-not-found
  147. IPP_GONE = 0x0407 # client-error-gone
  148. IPP_REQUEST_ENTITY = 0x0408 # client-error-request-entity-too-large
  149. IPP_REQUEST_VALUE = 0x0409 # client-error-request-value-too-long
  150. IPP_DOCUMENT_FORMAT = 0x040a # client-error-document-format-not-supported
  151. IPP_ATTRIBUTES = 0x040b # client-error-attributes-or-values-not-supported
  152. IPP_URI_SCHEME = 0x040c # client-error-uri-scheme-not-supported
  153. IPP_CHARSET = 0x040d # client-error-charset-not-supported
  154. IPP_CONFLICT = 0x040e # client-error-conflicting-attributes
  155. IPP_COMPRESSION_NOT_SUPPORTED = 0x040f # client-error-compression-not-supported
  156. IPP_COMPRESSION_ERROR = 0x0410 # client-error-compression-error
  157. IPP_DOCUMENT_FORMAT_ERROR = 0x0411 # client-error-document-format-error
  158. IPP_DOCUMENT_ACCESS_ERROR = 0x0412 # client-error-document-access-error
  159. IPP_ATTRIBUTES_NOT_SETTABLE = 0x0413 # client-error-attributes-not-settable
  160. IPP_IGNORED_ALL_SUBSCRIPTIONS = 0x0414 # client-error-ignored-all-subscriptions
  161. IPP_TOO_MANY_SUBSCRIPTIONS = 0x0415 # client-error-too-many-subscriptions
  162. IPP_IGNORED_ALL_NOTIFICATIONS = 0x0416 # client-error-ignored-all-notifications
  163. IPP_PRINT_SUPPORT_FILE_NOT_FOUND = 0x0417 # client-error-print-support-file-not-found
  164. IPP_INTERNAL_ERROR = 0x0500 # server-error-internal-error
  165. IPP_OPERATION_NOT_SUPPORTED = 0x0501 # server-error-operation-not-supported
  166. IPP_SERVICE_UNAVAILABLE = 0x0502 # server-error-service-unavailable
  167. IPP_VERSION_NOT_SUPPORTED = 0x0503 # server-error-version-not-supported
  168. IPP_DEVICE_ERROR = 0x0504 # server-error-device-error
  169. IPP_TEMPORARY_ERROR = 0x0505 # server-error-temporary-error
  170. IPP_NOT_ACCEPTING = 0x0506 # server-error-not-accepting-jobs
  171. IPP_PRINTER_BUSY = 0x0507 # server-error-busy
  172. IPP_ERROR_JOB_CANCELLED = 0x0508 # server-error-job-canceled
  173. IPP_MULTIPLE_JOBS_NOT_SUPPORTED = 0x0509 # server-error-multiple-document-jobs-not-supported
  174. IPP_PRINTER_IS_DEACTIVATED = 0x050a # server-error-printer-is-deactivated
  175.  
  176. CUPS_ERROR_BAD_NAME = 0x0f00
  177. CUPS_ERROR_BAD_PARAMETERS = 0x0f01
  178.  
  179. nickname_pat = re.compile(r'''\*NickName:\s*\"(.*)"''', re.MULTILINE)
  180. pat_cups_error_log = re.compile("""^loglevel\s?(debug|debug2|warn|info|error|none)""", re.I)
  181. ppd_pat = re.compile(r'''.*hp-(.*?)(-.*)+\.ppd.*''', re.I)
  182.  
  183.  
  184.  
  185. def getPPDPath(addtional_paths=None):
  186.     """
  187.         Returns the CUPS ppd path (not the foomatic one under /usr/share/ppd).
  188.         Usually this is /usr/share/cups/model.
  189.     """
  190.     if addtional_paths is None:
  191.         addtional_paths = []
  192.  
  193.     search_paths = prop.ppd_search_path.split(';') + addtional_paths
  194.  
  195.     for path in search_paths:
  196.         ppd_path = os.path.join(path, 'cups/model')
  197.         if os.path.exists(ppd_path):
  198.             return ppd_path
  199.  
  200.  
  201. def getAllowableMIMETypes():
  202.     """
  203.         Scan all /etc/cups/*.convs files for allowable file formats.
  204.     """
  205.     files = glob.glob("/etc/cups/*.convs")
  206.  
  207.     allowable_mime_types = []
  208.  
  209.     for f in files:
  210.         #log.debug( "Capturing allowable MIME types from: %s" % f )
  211.         conv_file = file(f, 'r')
  212.  
  213.         for line in conv_file:
  214.             if not line.startswith("#") and len(line) > 1:
  215.                 try:
  216.                     source, dest, cost, prog =  line.split()
  217.                 except ValueError:
  218.                     continue
  219.  
  220.                 if source not in ('application/octet-stream', 'application/vnd.cups-postscript'):
  221.                     allowable_mime_types.append(source)
  222.  
  223.     # Add some well-known MIME types that may not appear in the .convs files
  224.     allowable_mime_types.append("image/x-bmp")
  225.     allowable_mime_types.append("text/cpp")
  226.     allowable_mime_types.append("application/x-python")
  227.     allowable_mime_types.append("application/hplip-fax")
  228.  
  229.     return allowable_mime_types
  230.  
  231.  
  232. def getPPDDescription(f):
  233.     if f.endswith('.gz'):
  234.         nickname = gzip.GzipFile(f, 'r').read(4096)
  235.     else:
  236.         nickname = file(f, 'r').read(4096)
  237.  
  238.     try:
  239.         desc = nickname_pat.search(nickname).group(1)
  240.     except AttributeError:
  241.         desc = ''
  242.  
  243.     return desc
  244.  
  245.  
  246. def getSystemPPDs():
  247.     major, minor, patch = getVersionTuple()
  248.     ppds = {} # {'ppd name' : 'desc', ...}
  249.  
  250.     if major == 1 and minor < 2:
  251.         ppd_dir = sys_conf.get('dirs', 'ppd')
  252.         log.debug("(CUPS 1.1.x) Searching for PPDs in: %s" % ppd_dir)
  253.  
  254.         for f in utils.walkFiles(ppd_dir, pattern="HP*ppd*;hp*ppd*", abs_paths=True):
  255.             desc = getPPDDescription(f)
  256.  
  257.             if not ('foo2' in desc or
  258.                     'gutenprint' in desc.lower() or
  259.                     'gutenprint' in f):
  260.  
  261.                 ppds[f] = desc
  262.                 log.debug("%s: %s" % (f, desc))
  263.  
  264.     else: # 1.2.x
  265.         log.debug("(CUPS 1.2.x) Getting list of PPDs using CUPS_GET_PPDS...")
  266.         ppd_dict = cupsext.getPPDList()
  267.         cups_ppd_path = getPPDPath() # usually /usr/share/cups/model
  268.         foomatic_ppd_path = sys_conf.get('dirs', 'ppdbase', '/usr/share/ppd')
  269.  
  270.         if not foomatic_ppd_path or not os.path.exists(foomatic_ppd_path):
  271.             foomatic_ppd_path = '/usr/share/ppd'
  272.  
  273.         log.debug("CUPS PPD base path = %s" % cups_ppd_path)
  274.         log.debug("Foomatic PPD base path = %s" % foomatic_ppd_path)
  275.  
  276.         for ppd in ppd_dict:
  277.             if not ppd:
  278.                 continue
  279.  
  280.             if 'hp-' in ppd.lower() or 'hp_' in ppd.lower() and \
  281.                 ppd_dict[ppd]['ppd-make'] == 'HP':
  282.  
  283.                 desc = ppd_dict[ppd]['ppd-make-and-model']
  284.                 #print ppd, desc
  285.  
  286.                 if not ('foo2' in desc.lower() or
  287.                         'gutenprint' in desc.lower() or
  288.                         'gutenprint' in ppd):
  289.  
  290.                     # PPD files returned by CUPS_GET_PPDS (and by lpinfo -m)
  291.                     # can be relative to /usr/share/ppd/ or to
  292.                     # /usr/share/cups/model/. Not sure why this is.
  293.                     # Here we will try both and see which one it is...
  294.  
  295.                     if os.path.exists(ppd):
  296.                         path = ppd
  297.                     else:
  298.                         try:
  299.                             path = os.path.join(foomatic_ppd_path, ppd)
  300.                         except AttributeError: # happens on some boxes with provider: style ppds (foomatic: etc)
  301.                             path = ppd
  302.                         else:
  303.                             if not os.path.exists(path):
  304.                                 try:
  305.                                     path = os.path.join(cups_ppd_path, ppd)
  306.                                 except AttributeError:
  307.                                     path = ppd
  308.                                 else:
  309.                                     if not os.path.exists(path):
  310.                                         path = ppd # foomatic: or some other driver
  311.  
  312.                     ppds[path] = desc
  313.                     #log.debug("%s: %s" % (path, desc))
  314.  
  315.     return ppds
  316.  
  317.  
  318. ## TODO: Move this to CUPSEXT for better performance
  319. def levenshtein_distance(a,b):
  320.     """
  321.     Calculates the Levenshtein distance between a and b.
  322.     Written by Magnus Lie Hetland.
  323.     """
  324.     n, m = len(a), len(b)
  325.     if n > m:
  326.         a,b = b,a
  327.         n,m = m,n
  328.  
  329.     current = range(n+1)
  330.     for i in range(1,m+1):
  331.         previous, current = current, [i]+[0]*m
  332.  
  333.         for j in range(1,n+1):
  334.             add, delete = previous[j]+1, current[j-1]+1
  335.             change = previous[j-1]
  336.  
  337.             if a[j-1] != b[i-1]:
  338.                 change = change + 1
  339.  
  340.             current[j] = min(add, delete, change)
  341.  
  342.     return current[n]
  343.  
  344.  
  345. number_pat = re.compile(r""".*?(\d+)""", re.IGNORECASE)
  346.  
  347.  
  348. STRIP_STRINGS2 = ['foomatic:', 'hp-', 'hp_', 'hp ', '.gz', '.ppd',
  349.                  '-hpijs', 'drv:', '-pcl', '-pcl3', '-jetready',
  350.                  '-zxs', '-zjs', '-ps', '-postscript',
  351.                  '-jr', '-lidl', '-lidil', '-ldl']
  352.  
  353.  
  354. for p in models.TECH_CLASS_PDLS.values():
  355.     pp = '-%s' % p
  356.     if pp not in STRIP_STRINGS2:
  357.         STRIP_STRINGS2.append(pp)
  358.  
  359.  
  360. STRIP_STRINGS = STRIP_STRINGS2[:]
  361. STRIP_STRINGS.extend(['-series', ' series', '_series'])
  362.  
  363.  
  364. def stripModel2(model): # For new 2.8.10+ PPD find algorithm
  365.     model = model.lower()
  366.  
  367.     for x in STRIP_STRINGS2:
  368.         model = model.replace(x, '')
  369.  
  370.     return model
  371.  
  372.  
  373. def stripModel(model): # for old PPD find algorithm (removes "series" as well)
  374.     model = model.lower()
  375.  
  376.     for x in STRIP_STRINGS:
  377.         model = model.replace(x, '')
  378.  
  379.     return model
  380.  
  381.  
  382. def getPPDFile(stripped_model, ppds): # Old PPD find
  383.     """
  384.         Match up a model name to a PPD from a list of system PPD files.
  385.     """
  386.     log.debug("1st stage edit distance match")
  387.     mins = {}
  388.     eds = {}
  389.     min_edit_distance = sys.maxint
  390.  
  391.     log.debug("Determining edit distance from %s (only showing edit distances < 4)..." % stripped_model)
  392.     for f in ppds:
  393.         t = stripModel(os.path.basename(f))
  394.         eds[f] = levenshtein_distance(stripped_model, t)
  395.         if eds[f] < 4:
  396.             log.debug("dist('%s') = %d" % (t, eds[f]))
  397.         min_edit_distance = min(min_edit_distance, eds[f])
  398.  
  399.     log.debug("Min. dist = %d" % min_edit_distance)
  400.  
  401.     for f in ppds:
  402.         if eds[f] == min_edit_distance:
  403.             for m in mins:
  404.                 if os.path.basename(m) == os.path.basename(f):
  405.                     break # File already in list possibly with different path (Ubuntu, etc)
  406.             else:
  407.                 mins[f] = ppds[f]
  408.  
  409.     log.debug(mins)
  410.  
  411.     if len(mins) > 1: # try pattern matching the model number
  412.         log.debug("2nd stage matching with model number")
  413.  
  414.         try:
  415.             model_number = number_pat.match(stripped_model).group(1)
  416.             model_number = int(model_number)
  417.         except AttributeError:
  418.             pass
  419.         except ValueError:
  420.             pass
  421.         else:
  422.             log.debug("model_number=%d" % model_number)
  423.             matches = {} #[]
  424.             for x in range(3): # 1, 10, 100
  425.                 factor = 10**x
  426.                 log.debug("Factor = %d" % factor)
  427.                 adj_model_number = int(model_number/factor)*factor
  428.                 number_matching, match = 0, ''
  429.  
  430.                 for m in mins:
  431.                     try:
  432.                         mins_model_number = number_pat.match(os.path.basename(m)).group(1)
  433.                         mins_model_number = int(mins_model_number)
  434.                         log.debug("mins_model_number= %d" % mins_model_number)
  435.                     except AttributeError:
  436.                         continue
  437.                     except ValueError:
  438.                         continue
  439.  
  440.                     mins_adj_model_number = int(mins_model_number/factor)*factor
  441.                     log.debug("mins_adj_model_number=%d" % mins_adj_model_number)
  442.                     log.debug("adj_model_number=%d" % adj_model_number)
  443.  
  444.                     if mins_adj_model_number == adj_model_number:
  445.                         log.debug("match")
  446.                         number_matching += 1
  447.                         matches[m] = ppds[m]
  448.                         log.debug(matches)
  449.  
  450.                     log.debug("***")
  451.  
  452.                 if len(matches):
  453.                     mins = matches
  454.                     break
  455.  
  456.     return mins
  457.  
  458.  
  459. def getPPDFile2(stripped_model, ppds): # New PPD find
  460.     # This routine is for the new PPD naming scheme begun in 2.8.10
  461.     # and beginning with implementation in 2.8.12 (Qt4 hp-setup)
  462.     # hp-<model name from models.dat w/o beginning hp_>[-<pdl>][-<pdl>][...].ppd[.gz]
  463.     log.debug("Matching PPD list to model %s..." % stripped_model)
  464.     matches = []
  465.     for f in ppds:
  466.         match = ppd_pat.match(f)
  467.         if match is not None:
  468.             if match.group(1) == stripped_model:
  469.                 log.debug("Found match: %s" % f)
  470.                 pdls = match.group(2).split('-')
  471.                 matches.append((f, [p for p in pdls if p and p != 'hpijs']))
  472.  
  473.     log.debug(matches)
  474.     num_matches = len(matches)
  475.  
  476.     if num_matches == 0:
  477.         log.error("No PPD found for model %s. Trying old algorithm..." % stripped_model)
  478.         matches = getPPDFile(stripModel(stripped_model), ppds).items()
  479.         log.debug(matches)
  480.         num_matches = len(matches)
  481.  
  482.     if num_matches == 0:
  483.         log.error("No PPD found for model %s using old algorithm." % stripModel(stripped_model))
  484.         return None
  485.  
  486.     elif num_matches == 1:
  487.         log.debug("One match found.")
  488.         return (matches[0][0], '')
  489.  
  490.     # > 1
  491.     log.debug("%d matches found. Selecting based on PDL: Host > PS > PCL/Other" % num_matches)
  492.     for p in [models.PDL_TYPE_HOST, models.PDL_TYPE_PS, models.PDL_TYPE_PCL]:
  493.         for m in matches:
  494.             for x in m[1]:
  495.                 # default to HOST-based PDLs, as newly supported PDLs will most likely be of this type
  496.                 if models.PDL_TYPES.get(x, models.PDL_TYPE_HOST) == p:
  497.                     log.debug("Selecting '-%s' PPD: %s" % (x, m[0]))
  498.                     return (m[0], '')
  499.  
  500.     # No specific PDL found, so just return 1st found PPD file
  501.     # (e.g., files only have -hpijs, no PDL indicators)
  502.     log.debug("No specific PDL located. Defaulting to first found PPD file.")
  503.     return (matches[0][0], '')
  504.  
  505.  
  506.  
  507. def getErrorLogLevel():
  508.     cups_conf = '/etc/cups/cupsd.conf'
  509.     try:
  510.         f = file(cups_conf, 'r')
  511.     except OSError:
  512.         log.error("%s not found." % cups_conf)
  513.     except IOError:
  514.         log.error("%s: I/O error." % cups_conf)
  515.     else:
  516.         for l in f:
  517.             m = pat_cups_error_log.match(l)
  518.             if m is not None:
  519.                 level = m.group(1).lower()
  520.                 log.debug("CUPS error_log LogLevel: %s" % level)
  521.                 return level
  522.  
  523.     log.debug("CUPS error_log LogLevel: unknown")
  524.     return 'unknown'
  525.  
  526.  
  527. def getPrintJobErrorLog(job_id, max_lines=1000, cont_interval=5):
  528.     ret = []
  529.     s = '[Job %d]' % job_id
  530.     #level = getErrorLogLevel()
  531.     cups_conf = '/var/log/cups/error_log'
  532.  
  533.     #if level in ('debug', 'debug2'):
  534.     if 1:
  535.         try:
  536.             f = file(cups_conf, 'r')
  537.         except (IOError, OSError):
  538.             log.error("Could not open the CUPS error_log file: %s" % cups_conf)
  539.             return ''
  540.  
  541.         else:
  542.             if s in file(cups_conf, 'r').read():
  543.                 queue = utils.Queue()
  544.                 job_found = False
  545.  
  546.                 while True:
  547.                     line = f.readline()
  548.  
  549.                     if s in line:
  550.                         job_found = True
  551.  
  552.                         while len(queue):
  553.                             ret.append(queue.get())
  554.  
  555.                         ret.append(line.strip())
  556.  
  557.                         if len(ret) > max_lines:
  558.                             break
  559.  
  560.                     else:
  561.                         if job_found:
  562.                             queue.put(line.strip())
  563.  
  564.                             if len(queue) > cont_interval:
  565.                                 break
  566.  
  567.             return '\n'.join(ret)
  568.  
  569.  
  570. #
  571. # cupsext wrappers
  572. #
  573.  
  574. def getDefaultPrinter():
  575.     r = cupsext.getDefaultPrinter()
  576.     if r is None:
  577.         log.debug("The CUPS default printer is not set.")
  578.     return r
  579.  
  580. def setDefaultPrinter(printer_name):
  581.     return cupsext.setDefaultPrinter(printer_name)
  582.  
  583. def accept(printer_name):
  584.     return controlPrinter(printer_name, CUPS_ACCEPT_JOBS)
  585.  
  586. def reject(printer_name):
  587.     return controlPrinter(printer_name, CUPS_REJECT_JOBS)
  588.  
  589. def start(printer_name):
  590.     return controlPrinter(printer_name, IPP_RESUME_PRINTER)
  591.  
  592. def stop(printer_name):
  593.     return controlPrinter(printer_name, IPP_PAUSE_PRINTER)
  594.  
  595. def purge(printer_name):
  596.     return controlPrinter(printer_name, IPP_PURGE_JOBS)
  597.  
  598. def controlPrinter(printer_name, cups_op):
  599.     if cups_op in (CUPS_ACCEPT_JOBS, CUPS_REJECT_JOBS, IPP_PAUSE_PRINTER, IPP_RESUME_PRINTER, IPP_PURGE_JOBS):
  600.         return cupsext.controlPrinter(printer_name, cups_op)
  601.  
  602.     return 0;
  603.  
  604. def openPPD(printer):
  605.     if not printer:
  606.         return
  607.  
  608.     return cupsext.openPPD(printer)
  609.  
  610. def closePPD():
  611.     return cupsext.closePPD()
  612.  
  613. def getPPD(printer):
  614.     if not printer:
  615.         return
  616.  
  617.     return cupsext.getPPD(printer)
  618.  
  619. def getPPDOption(option):
  620.     return cupsext.getPPDOption(option)
  621.  
  622. def getPPDPageSize():
  623.     return cupsext.getPPDPageSize()
  624.  
  625. def getPrinters():
  626. ##    p2 = []
  627. ##    p = cupsext.getPrinters()
  628. ##    for pp in p:
  629. ##        print pp
  630. ##        try:
  631. ##            pn = pp.name.decode('utf-8')
  632. ##        except UnicodeError:
  633. ##            pass
  634. ##
  635. ##        p2.append(pp)
  636. ##
  637. ##    return p2
  638.     return cupsext.getPrinters()
  639.  
  640. def getJobs(my_job=0, completed=0):
  641.     return cupsext.getJobs(my_job, completed)
  642.  
  643. def getAllJobs(my_job=0):
  644.     return cupsext.getJobs(my_job, 0) + cupsext.getJobs(my_job, 1)
  645.  
  646. def getVersion():
  647.     return cupsext.getVersion()
  648.  
  649. def getVersionTuple():
  650.     return cupsext.getVersionTuple()
  651.  
  652. def getServer():
  653.     return cupsext.getServer()
  654.  
  655. def cancelJob(jobid, dest=None):
  656.     if dest is not None:
  657.         return cupsext.cancelJob(dest, jobid)
  658.     else:
  659.         jobs = cupsext.getJobs(0, 0)
  660.         for j in jobs:
  661.             if j.id == jobid:
  662.                 return cupsext.cancelJob(j.dest, jobid)
  663.  
  664.     return False
  665.  
  666. def resetOptions():
  667.     return cupsext.resetOptions()
  668.  
  669. def addOption(option):
  670.     return cupsext.addOption(option)
  671.  
  672. def getOptions():
  673.     return cupsext.getOptions()
  674.  
  675. def printFile(printer, filename, title):
  676.     if os.path.exists(filename):
  677.         return cupsext.printFileWithOptions(printer, filename, title)
  678.     else:
  679.         return -1
  680.  
  681. def addPrinter(printer_name, device_uri, location, ppd_file, model, info):
  682.     log.debug("addPrinter('%s', '%s', '%s', '%s', '%s', '%s')" %
  683.         ( printer_name, device_uri, location, ppd_file, model, info))
  684.  
  685.     if ppd_file and not os.path.exists(ppd_file):
  686.         log.error("PPD file '%s' not found." % ppd_file)
  687.         return (-1, "PPD file not found")
  688.  
  689.     return cupsext.addPrinter(printer_name, device_uri, location, ppd_file, model, info)
  690.  
  691. def delPrinter(printer_name):
  692.     return cupsext.delPrinter(printer_name)
  693.  
  694. def getGroupList():
  695.     return cupsext.getGroupList()
  696.  
  697. def getGroup(group):
  698.     return cupsext.getGroup(group)
  699.  
  700. def getOptionList(group):
  701.     return cupsext.getOptionList(group)
  702.  
  703. def getOption(group, option):
  704.     return cupsext.getOption(group, option)
  705.  
  706. def getChoiceList(group, option):
  707.     return cupsext.getChoiceList(group, option)
  708.  
  709. def getChoice(group, option, choice):
  710.     return cupsext.getChoice(group, option, choice)
  711.  
  712. def setOptions():
  713.     return cupsext.setOptions()
  714.  
  715. def removeOption(option):
  716.     return cupsext.removeOption(option)
  717.  
  718. def setPasswordCallback(func):
  719.     return cupsext.setPasswordCallback(func)
  720.  
  721.